import { useState } from 'react';
import { connect } from 'react-redux';


function PersonInfo(props) {
  const [info, setInfo] = useState({ name: null, age: null, gender: null });

  // 这里创建的是ref容器
  let refName = null;
  let refAge = null;

  const collectInfo = (type) => (e) => {
    switch (type) {
      case 'name':
        setInfo(state => {
          return { ...state, name: e.target.value };
        })
        break;
      case 'gender':
        setInfo(state => {
          return { ...state, gender: e.target.value };
        })
        break;
      case 'age':
        setInfo(state => {
          return { ...state, age: e.target.value }
        })
        break
      default:
        throw new Error('message error.')
    }
  }

  const handleClick = () => {
    if (Object.keys(info).find(item => info[item] === null)) return
    props.dispatch({ type: 'INCREMENT_INFO', payload: info })

  }

  return (
    <div>
      <div>
        <span>姓名：</span>
        <input type="text" placeholder='姓名' onChange={collectInfo('name')} ref={r => refName = r} />
      </div>
      <div>
        <span>姓别：</span>
        <label >
          <input type="radio" id='male' value={0} name='gender' onChange={collectInfo('gender')} />男
        </label>
        <label >
          <input type="radio" id='female' value={1} name='gender' onChange={collectInfo('gender')} />女
        </label>
      </div>
      <div>
        <span>年龄:</span>
        <input type="number" placeholder='年龄' onChange={collectInfo('age')} ref={r => refAge = r} />
      </div>
      <div>
        <button onClick={handleClick}>添加</button>
      </div>
    </div>
  )
}

export default connect()(PersonInfo)